package top.lishuoboy.jwt.jwt.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.lishuoboy.dependency.base.json.HuJsonUtil;
import top.lishuoboy.jwt.jwt.bean.User;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author lishuoboy
 * @date 2022/4/18 11:49
 */
@Slf4j
@Controller
public class LoginController {
    /* 初始化用户数据 */
    private static final Map<String, User> userMap = MapUtil.<String, User>builder()
        .put("zhangsan", new User("zhangsan", "111111"))
        .put("lisi", new User("lisi", "222222"))
        .build();


    @GetMapping("/login")
    @ResponseBody
    private String login(User user) {
        String name = user.getName();
        if (!userMap.containsKey(name)) {
            return "用户【" + name + "】不存在";
        }
        if (!userMap.get(name).getPwd().equals(user.getPwd())) {
            return "用户【" + name + "】密码错误";
        }
        Map header = MapUtil.builder("alg", "HS256").put("typ", "JWT").build();
        Map payload = MapUtil.<String, Object>builder()
            .put("creationTime", DateUtil.current())
            .put("validTime", DateUtil.current() + 1 * 60 * 1000)
            .put("user", HuJsonUtil.toMap(HuJsonUtil.toJsonStr(user)))
            .build();

        String token = JWT.create().withHeader(header)
            .withPayload(payload)
            .sign(Algorithm.HMAC256("111111".getBytes(StandardCharsets.UTF_8)));

        return token;
    }

    @GetMapping("/main")
    @ResponseBody
    private String main() {
        return "main";
    }
}
